/*
 * Copyright 2012 Nicholas Bilyk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package Util {
	
    import cocos2d.CCSprite;
    import cocos2d.CCSpriteFrame;
    import cocos2d.CCSpriteFrameCache;
    import cocos2d.CCAnimation;
    import cocos2d.CCArray;

	class ViewUtil {

        /**
         * A convenience method to create a CCSprite from the given frame name.
         * This assumes the frame cache has already been set.
         */
		public static function createSprite(frameName:String):CCSprite {
            var cache:CCSpriteFrameCache = CCSpriteFrameCache.sharedSpriteFrameCache();
            var frame:CCSpriteFrame = cache.spriteFrameByName(frameName);
            return CCSprite.createWithSpriteFrame(frame);
		}

        /**
         * A convenience method to set the view's display frame. This assumes the frame cache
         * has already been set.
         */
        public static function setFrameByName(view:CCSprite, frameName:String):void {
            var cache:CCSpriteFrameCache = CCSpriteFrameCache.sharedSpriteFrameCache();
            var frame:CCSpriteFrame = cache.spriteFrameByName(frameName);
            view.setDisplayFrame(frame);
        }

        /**
         * Given our workflow of exporting spritesheets from Flash, Flash will name the frames
         * with the convention "Foo0000". This method will create an animation for a set of frames.
         * (0 indexed, to and from are inclusive, so createAnimation('Foo', 5, 10) will return the 
         * animation of the MovieClip's frames 6 through 11).
         */
        public static function createAnimation(prefix:String, from:uint, to:uint):CCAnimation {
            var anim:CCArray = CCArray.array();
            anim.retain();
            var cache:CCSpriteFrameCache = CCSpriteFrameCache.sharedSpriteFrameCache();
            for (var i:uint = from; i <= to; i++) {
                var frameName:String = prefix + NumberUtil.padNumber(i, 4);
                anim.addObject(cache.spriteFrameByName(frameName));
            }
            var animation:CCAnimation = CCAnimation.animationWithSpriteFrames(anim, 1.0/24.0);
            animation.retain();
            return animation;
        }
	}
}